﻿using UnityEngine;

namespace Core
{
    public interface ISlice
    {
        void Switch(int i);
        void SwitchNext();
        void SwitchPrev();
    }

    /// <summary>
    /// 前缀 slice_XXX 
    /// </summary>
    public class UISlice : UIWidget
    {
        private GameObject[] children;

        private GameObject curr;
        private int index;

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            index = 0;

            var cnt = transform.childCount;
            children = new GameObject[cnt];
            for (int i = 0; i < cnt; i++)
            {
                var child = transform.GetChild(i);
                if (child == null)
                {
                    continue;
                }

                children[i] = child.gameObject;

                Utils.Trans.SetActive(children[i], i == index);
            }
            if (cnt > 0)
            {
                curr = children[index];
            }
        }

        public override void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }
            base.Dispose();

            children = null;
            curr = null;
        }


        public void Switch(int i)
        {
            if (children == null) return;

            if (i < 0 || i >= children.Length)
            {
                return;
            }

            Utils.Trans.SetActive(curr, false);
            curr = children[i];
            index = i;
            Utils.Trans.SetActive(curr, true);
        }

        public void SwitchNext()
        {
            if (children == null) return;

            Switch((index + 1) % children.Length);
        }

        public void SwitchPrev()
        {
            if (children == null) return;

            Switch((index - 1 + children.Length) % children.Length);
        }
    }
}
